using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Camalon.Drawing.Shapes
{

	[ToolboxItem(true)]
	public class Triangle : Shape
	{

		private PointF _ptTop = PointF.Empty;

		public Triangle():base( new Rectangle( Point.Empty, new Size( 100,100)))
		{
			RectangleF bounds = base.Bounds;
			float horizontalCenter = bounds.Left + ((bounds.Right - bounds.Left)/2f);
			_ptTop = new PointF( horizontalCenter, bounds.Top );

		}

		protected override GraphicsPath MakePath(RectangleF bounds)
		{
			GraphicsPath path = new GraphicsPath();

			// Assign 3 points of the triangle
			PointF ptLeftBottom = new PointF( bounds.Left, bounds.Bottom );
			PointF ptRightBottom = new PointF( bounds.Right, bounds.Bottom );
			
			// Add lines, which make the triangle, to the path
			PointF[] points = new PointF[]{ ptLeftBottom, ptRightBottom, _ptTop};	
			path.AddLines( points );
			
			//Close lines
			path.CloseFigure();

			//Return your path to the Shape-Subsystem		
			return path;
		}


		[Browsable( false)]
		[DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden)]
		public override PointF[] ControlPoints
		{
			get
			{
				return new PointF[]{ _ptTop };
			}
			set
			{
				_ptTop = value[0];
				//Snap the point on the top border of the bounding rectangle
				SnapPoint(true);
			}
		}


		// You need this property to serialize the top point. This is needed, 
		// if you want to that your shape restores this point in Design-Time.
		[DefaultValue( typeof( Point), "Empty")]
		public Point TopLocation
		{
			get
			{
				return Point.Round( _ptTop );
			}

			set
			{
				_ptTop = value;
				SnapPoint(true);
			}

		}


		private void SnapPoint(bool resetPath)
		{
			//Snap the point on the top border of the bounding rectangle
			RectangleF bounds = this.Bounds;
			if( _ptTop.X < bounds.Left ) _ptTop.X = bounds.Left;
			if( _ptTop.X > bounds.Right ) _ptTop.X = bounds.Right;
			_ptTop.Y = bounds.Top;

			//Force to remake path. This causes MakePath method to be called!
			if( resetPath ) ResetPath();

		}

		
		protected override void OnBoundsChanged(ValueChangeEventArgs eventArg)
		{
			//We translate the point if the shapes moves 
			RectangleF oldBounds = (RectangleF)eventArg.OldValue;
			RectangleF newBounds = (RectangleF)eventArg.NewValue;

			//Find out diff. values in X and Y direction.
			float dx = newBounds.Location.X - oldBounds.Location.X;
			float dy = newBounds.Location.Y - oldBounds.Location.Y;
			
			// Move your point also...
			_ptTop.X += dx;
			_ptTop.Y += dy;

			SnapPoint(false);

			base.OnBoundsChanged (eventArg);
		}

	}


}
